package main

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"embed"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io"
	"math/rand/v2"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

func zhengzemain() {
	fmt.Println("================zhengze==========")
	match, _ := regexp.MatchString("p([a-z]+)ch", "peachasdasdasdas")
	fmt.Println(match)
	r, _ := regexp.Compile("[a-z]+")
	fmt.Println(r.MatchString("a"))
	fmt.Println("idx:", r.FindStringIndex("d"))
	fmt.Println(r.FindAllString("pinch", -1))

	fmt.Println(r.FindStringSubmatchIndex("peach punch"))

	fmt.Println(r.FindAllString("peach punch pinch", -1))

	r = regexp.MustCompile("p([a-z]+)ch")

	fmt.Println("regexp:", r)
	in := []byte("a peach")
	out := r.ReplaceAllFunc(in, bytes.ToUpper)
	fmt.Println("ddddddddddd: ", string(out))
	bolb, _ := json.Marshal(true)
	fmt.Println(string(bolb))

	intB, _ := json.Marshal(1)
	fmt.Println(string(intB))
	res1D := &response1{
		Page:   11,
		Fruits: []string{"apple", "peach", "punch"},
	}
	res2b, _ := json.Marshal(res1D)
	fmt.Println("res2b json: ", string(res2b))

	res := response1{}
	err := json.Unmarshal([]byte(string(res2b)), &res)
	if err != nil {
		return
	}
	fmt.Println("res2b json class:", res)
	xmljson()
	pathTempsCreate()
	embedasasd()
}

type response1 struct {
	Page   int
	Fruits []string
}
type response2 struct {
	Page   int      `json:"page"`
	Fruits []string `json:"fruits"`
}
type Plant struct {
	XMLName xml.Name `xml:"plant"`
	Id      int      `xml:"id,attr"`
	Name    string   `xml:"name"`
	Origin  []string `xml:"origin"`
}

func (p Plant) String() string {
	return fmt.Sprintf("id:%d name:%s origin:%v", p.Id, p.Name, p.Origin)
}
func xmljson() {
	coffee := &Plant{Id: 27, Name: "Coffee"}
	coffee.Origin = []string{"Ethiopia", "Brazil"}
	out, _ := xml.MarshalIndent(coffee, " ", "  ")
	fmt.Println("yi:", xml.Header+string(out))
	var p Plant
	err := xml.Unmarshal(out, &p)
	if err != nil {
		panic(err)
	}
	fmt.Println("p: ", p)
	tomato := &Plant{Id: 81, Name: "Names"}
	tomato.Origin = []string{"Mexico", "California"}
	out, _ = xml.MarshalIndent(tomato, " ", "  ")
	fmt.Println("er:", xml.Header+string(out))

	tomato = &Plant{Id: 86, Name: "Names6"}
	tomato.Origin = []string{"Mexico66", "California66"}
	out, _ = xml.MarshalIndent(tomato, " ", "  ")
	fmt.Println("er2 :", xml.Header+string(out))
	timemain()
	Unixsd()
	timejsonUnmxml()
}
func timemain() {
	p := fmt.Println
	now := time.Now()
	p(now)
	then := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
	p(then)
	p(then.Year())
	p(then.YearDay())
	p(then.Month())
	p(then.Day())
	p(then.Hour())
	p(then.Minute())
	p(then.Second())
	p(then.Nanosecond())
	p(then.Weekday())

	diff := now.Sub(then)
	p(diff)
	p(diff.Hours())
	p(diff.Minutes())
	p(diff.Seconds())
	p(diff.Nanoseconds())

	p(then.Add(24 * time.Hour))
	p(then.Add(diff))
	p(then.Add(-diff))
}
func Unixsd() {
	fmt.Println("======UnixsdUnixsdUnixsdUnixsd==")
	now := time.Now()
	p(now)
	p(now.Unix())
	p(now.UnixMilli())
	p(now.UnixMicro())
	p(now.Nanosecond())
	p(time.Unix(0, now.UnixNano()))
}
func timejsonUnmxml() {
	fmt.Println("========timejsonUnmxml==========")
	t := time.Now()
	p(t.Format("2006-01-02 15:04:05"))
	p(t.Format("3.05PM"))
	ansic := "Mon Jan _2 15:04:05 2006"
	_, e := time.Parse(ansic, "8:41PM")
	p(e)
	p(rand.Int32N(100), ",")
	p(rand.Int32N(100))
	fmt.Println()
	fmt.Println("rand===============")
	fmt.Println(rand.Float64())
	s2 := rand.NewPCG(1, 10)
	r2 := rand.New(s2)
	fmt.Println(r2.IntN(100))
	fmt.Print(r2.IntN(100), ",")

	s3 := rand.NewPCG(42, 1024)
	r3 := rand.New(s3)
	fmt.Print(r3.IntN(100), ",")
	fmt.Print(r3.IntN(100))

	f, _ := strconv.ParseFloat("1.234", 64)
	p(" f:", f)
	i, _ := strconv.ParseInt("123", 0, 64)
	p(" i:", i)
	a, _ := strconv.ParseInt("0x1c8", 0, 64)
	p(" a:", a)
	u, _ := strconv.ParseUint("789", 0, 64)
	w, _ := strconv.Atoi("789")
	fmt.Println("u:", w)
	fmt.Println("u:", u)
	//urltest()
	readFiles()
}

const urls = "postgres://user:pass@host.com:5432/path?k=v#f"

func urltest() {
	fmt.Println(urls)

	u, err := url.Parse(urls)
	if err != nil {
		panic(err)
	}
	fmt.Println(u.Scheme)
	fmt.Println(u.User)
	fmt.Println(u.Port())
	fmt.Println(u.RawQuery)
	m, _ := url.ParseQuery(u.RawQuery)
	fmt.Println(u.Host)
	fmt.Println(u.Path)
	p(u.Query())
	fmt.Printf("url path raw query : %s", m["k"][0])
	sha256hash()
}
func sha256hash() {
	fmt.Println("===============================sha256hash")
	var s = "shar 256 this hash"
	h := sha256.New()
	h.Write([]byte(s))
	var bs = h.Sum(nil)
	fmt.Printf("%s\n", s)
	fmt.Printf("%x\n", bs)
	fmt.Printf("%x\n", bs)

	data := "孔韶波"
	hash := sha256.Sum256([]byte(data))

	// 将哈希结果编码为十六进制字符串
	hexEncoded := hex.EncodeToString(hash[:])
	fmt.Println("SHA256 (hex):", hexEncoded)

	// 将哈希结果编码为 Base64 字符串
	base64Encoded := base64.StdEncoding.EncodeToString(hash[:])
	fmt.Println("SHA256 (base64):", base64Encoded)

	//base 64 decode  encoding
	var data2 = "abc123"
	var enco = base64.StdEncoding.EncodeToString([]byte(data2))
	fmt.Println("Base64 begin :", enco)

	encodings, _ := base64.StdEncoding.DecodeString(enco)
	fmt.Println("Base64: end :", string(encodings))

}
func checks(e error) {
	if e != nil {
		panic(e)
	}
}
func readFiles() {
	data, err := os.ReadFile("C:\\Users\\Shaobokong\\Downloads\\player_EXT_0.log")
	checks(err)
	fmt.Println(string(data))

	f, err := os.Open("C:\\Users\\Shaobokong\\Downloads\\player_EXT_0.log")
	checks(err)

	b1 := make([]byte, 5)
	n1, err := f.Read(b1)
	checks(err)
	fmt.Println("%d bytes: %s \n", n1, string(b1[:n1]))
	da1, err1 := f.Seek(4, io.SeekCurrent)
	checks(err1)
	fmt.Println(da1)

	da2, err2 := f.Seek(-10, io.SeekEnd)
	checks(err2)
	fmt.Println(da2)

	r4 := bufio.NewReader(f)
	b4, err := r4.Peek(4)
	checks(err)
	fmt.Println(b4)
	f.Close()
	createFiles()
}
func createFiles() {
	d1 := []byte("hello \n go \n")
	err := os.WriteFile("C:\\Users\\Shaobokong\\Downloads\\player_EXT_0.log", d1, 0644)
	checks(err)
	f, err := os.Create("C:\\Users\\Shaobokong\\Downloads\\player_EXT_2.log")
	defer f.Close()
	checks(err)
	d2 := []byte{115, 111, 11, 112, 123, 33, 45}
	f2, err := f.Write(d2)
	checks(err)
	fmt.Println("wrote bytes f2 : ", f2)
	n3, err := f.WriteString("kso 孔宥芯")
	checks(err)
	fmt.Println("wrote bytes n3 : ", n3)

	w := bufio.NewWriter(f)
	writeString, err := w.WriteString(" {\n    \"audioShm\": \"A379059627ca2456cacf73fa92b272b7d\",\n    \"videoShm\": \"V379059627ca2456cacf73fa92b272b7d\",\n ")
	checks(err)
	fmt.Println("wrote bytes w : ", writeString)
	err4 := w.Flush()
	fmt.Println("wrote bytes err : ", err4)
	if err4 != nil {
		return
	}
	filepathJoin()
}
func LinesFilters() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		ucl := strings.ToUpper(scanner.Text())
		fmt.Println(ucl)
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
}
func filepathJoin() {
	p := filepath.Join("C:\\Users\\Shaobokong\\Downloads")
	fmt.Println(p)
	os.MkdirAll(p, os.ModePerm)
	p = filepath.Join(p, "ksod.ll")
	os.Create(p)
	d1 := []byte("hello \n go \n kso ")
	//for i := 0; i < 3; i++ {
	//	toAppend := []byte("additional data" + strconv.Itoa(i))
	//	s := append(d1, toAppend...)
	//	fmt.Println(string(s))
	//}
	err := os.WriteFile(p, d1, 0644)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
	}
	openFile, err := os.OpenFile(p, os.O_RDONLY|os.O_CREATE, 0666)
	if err != nil {
		panic(err)
	}
	defer func(openFile *os.File) {
		fmt.Println("asddddddddd")
		err := openFile.Close()
		if err != nil {
			panic(err)
		}
	}(openFile)
	for i := 0; i < 100; i++ {
		openFile.WriteString("孔宥芯" + strconv.Itoa(i))
		openFile.WriteString("孔宥芯" + strconv.Itoa(i))
		openFile.WriteString("孔宥芯" + strconv.Itoa(i))
		openFile.WriteString("孔宥芯" + strconv.Itoa(i))
		openFile.WriteString("孔宥芯" + strconv.Itoa(i) + "\n")
	}
	pathfileepath()
}
func pathfileepath() {
	err := os.Mkdir("subdir", os.ModePerm)
	if err != nil {
		return
	}
	checks(err)
	defer os.RemoveAll("subdir")
	creddd := func(name string) {
		d := []byte(name)
		checks(os.WriteFile(name, d, os.ModePerm))
	}

	err1 := os.MkdirAll("C:\\Users\\Shaobokong\\Downloads\\subdir/file3", os.ModePerm)
	if err1 != nil {
		return
	}
	os.MkdirAll("C:\\Users\\Shaobokong\\Downloads\\subdir\\file2", os.ModePerm)
	creddd("C:\\Users\\Shaobokong\\Downloads\\subdir/file1")
	dir, err := os.ReadDir("C:\\Users\\Shaobokong\\Downloads\\subdir/parent")
	if err != nil {
		return
	}
	for _, fi := range dir {
		fmt.Println(fi.Name())
	}
}

// 临时目录
func pathTempsCreate() {
	fmt.Println("=========path temp create ===========")
	f, err := os.CreateTemp("", "sample")
	if err != nil {
		return
	}
	fmt.Println(f.Name())
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
			fmt.Println(err)
		}
	}(f.Name())
	write, err := f.Write([]byte{1, 2, 3, 4})
	if err != nil {
		return
	}
	checks(err)
	fmt.Println("Temp dir name : ", write)
	defer func(path string) {
		err := os.RemoveAll(path)
		if err != nil {
			fmt.Println(err)
		}
	}(f.Name())
}

var (
	fileString string
	fileBytes  []byte
	folder     embed.FS
)

func embedasasd() {
	print(fileString)
	print(string(fileBytes))
	readDir, err := folder.ReadDir("C:\\Users\\Shaobokong\\Downloads")
	if err != nil {
		return
	}
	print(readDir)
}
